import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { TableC, ModalC, PrimaryC, PrimaryGhostC, UploadC, ProductGroupTreeC, InputNumberC, SingleDateC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { exportFile, isZiGuanEvir } from '../../../utils/commonFunc';
import myStyle from './index.less';
import uuid from 'es6-uuid';
import accounting from 'accounting';
import _ from 'lodash';

class MyModalC extends React.Component {
  constructor() {
    super();
    this.state = {
      columns: undefined,
      dataSource: undefined,
      pageSize: 10,
      currentPage: 1,
      isEdit: false, // 当前是否有编辑的行
      currentRow: {}, // 当前行编辑之前的数据
    };
  }

  componentDidMount() {
    this.initTable(); // 查询列表
  }

  // 查询表格的内容
  initTable = () => {
    this.props.dispatch({
      type: 'productManageM/getLiabilitySideInfo',
      payload: {
        productId: this.props.detailData.id,
      },
      callback: (data) => {
        this.formatDataSource(data); // 处理数据
      },
    });
  };

  formatDataSource = (data) => {
    this.changeColumns();
    if (data) {
      data.map((item) => {
        item.id = uuid(32);
        item.isEdit = false;
      });
      this.setState({
        dataSource: data || [],
      });
    } else {
      this.setState({
        dataSource: [],
      });
    }
  };

  // 每个表单变化
  elementChange = (type, e) => {
    const { dataSource, currentRow } = this.state;
    let currentData = e;
    if (['expectedYield', 'interestRate', 'placement'].indexOf(type) > -1) {
      if (e === '' || e == null) {
        currentData = undefined;
      } else if (type == 'expectedYield') currentData = parseFloat(e / 100);
    }
    dataSource.map((item) => {
      if (item.id == currentRow.id) {
        if (type == 'portfolioCode') {
          // 组合代码 组合名称取值
          item[type] = e?.key;
          item.portfolioName = e?.info.portfolioName;
        } else {
          item[type] = currentData;
        }
      }
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };

  // 组合代码排序
  handlerSoter = (a, b) => {
    return a.portfolioCode.localeCompare(b.portfolioCode);
  };

  // 处理columns
  changeColumns = () => {
    const {
      form: { getFieldValue },
    } = this.props;
    const columns = [
      {
        key: 'portfolioCode',
        title: '组合代码',
        render: (text, record) => {
          if (record.isEdit) {
            return (
              <ProductGroupTreeC
                form={this.props.form}
                title=''
                dataIndex='portfolioCode'
                multiple={false}
                onRef={(ref) => this.setState({ ProductGroupTreeC4: ref })}
                initialValue={text}
                productCode={this.props.detailData.gzCode}
                onChange={(e) => this.elementChange('portfolioCode', e)}
                positionBody={true}
              />
            );
          } else {
            return text || '--';
          }
        },
        sorter: this.state.isEdit ? undefined : this.handlerSoter,
        sortDirections: ['descend', 'ascend'],
      },
      {
        key: 'portfolioName',
        title: '组合名称',
        ellipsis: true,
      },
      {
        key: 'placement',
        title: '募集金额',
        align: 'right',
        width: 190,
        render: (text, record) => {
          if (record.isEdit) {
            return (
              <InputNumberC
                form={this.props.form}
                dataIndex='placement'
                initialValue={text}
                placeholder='请输入'
                min={0}
                splitStyle={true}
                precision={2}
                unit='元'
                // rules={[
                //     {pattern: /(^(?:\d|\d{0,12})(?:\.\d{0,2})?$)/, message:'字符不能超过15位！'}
                // ]}
                onChange={(e) => this.elementChange('placement', e)}
              />
            );
          } else {
            return text == null || text == undefined ? '--' : accounting.formatNumber(Number(text), 2);
          }
        },
      },
      {
        key: 'startDate',
        title: '起息日',
        width: 150,
        render: (text, record) => {
          if (record.isEdit) {
            return (
              <SingleDateC
                form={this.props.form}
                dataIndex='startDate'
                initialValue={text ? moment(text) : undefined}
                disableEnd={record.endDate ? moment(record.endDate) : undefined}
                allowClear={false}
                onChange={(e) => this.elementChange('startDate', e ? moment(e).format('YYYY-MM-DD') : moment(new Date()).format('YYYY-MM-DD'))}
              />
            );
          } else {
            return text || '--';
          }
        },
      },
      {
        key: 'endDate',
        title: '到期日',
        width: 150,
        render: (text, record) => {
          if (record.isEdit) {
            return (
              <SingleDateC
                form={this.props.form}
                dataIndex='endDate'
                initialValue={text ? moment(text) : undefined}
                disableBegin={record.startDate ? moment(record.startDate) : undefined}
                allowClear={false}
                onChange={(e) => this.elementChange('endDate', e ? moment(e).format('YYYY-MM-DD') : moment(new Date()).format('YYYY-MM-DD'))}
              />
            );
          } else {
            return text || '--';
          }
        },
      },
      {
        key: 'interestRate',
        title: '付息频率',
        align: 'right',
        width: 130,
        render: (text, record) => {
          if (record.isEdit) {
            return (
              <InputNumberC
                form={this.props.form}
                dataIndex='interestRate'
                initialValue={text}
                min={0}
                max={99}
                precision={0}
                placeholder='请输入'
                unit='次/年'
                onChange={(e) => this.elementChange('interestRate', e)}
              />
            );
          } else {
            return text == null || text == undefined ? '--' : `${text}次/年`;
          }
        },
      },
      {
        key: 'expectedYield',
        title: '年化预期收益率',
        width: 130,
        align: 'right',
        render: (text, record) => {
          if (record.isEdit) {
            return (
              <InputNumberC
                form={this.props.form}
                dataIndex='expectedYield'
                initialValue={text == undefined ? undefined : (text || 0) * 100}
                placeholder='请输入'
                min={0}
                max={999}
                step={0.01}
                precision={2}
                unit='%'
                onChange={(e) => this.elementChange('expectedYield', e)}
              />
            );
          } else {
            return text == null || text == undefined ? '--' : `${accounting.formatNumber((text || 0) * 100, 2)}%`;
          }
        },
      },
      {
        key: 'operate',
        type: 'operate',
        title: '操作',
        width: 110,
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.clickEdit(record);
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveRow(record);
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteRow(record);
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
            },
          },
          {
            title: '取消',
            onClick: (record, index) => {
              this.cancelRow(record);
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
            },
          },
        ],
      },
    ];
    this.setState({
      columns: [...columns],
    });
  };

  // 关闭弹窗
  closeModal = () => {
    this.props.onCancel();
  };

  // 点击确定按钮 进行提交到后端 提交成功关闭弹窗
  onOk = () => {
    const { dataSource = [] } = this.state;
    if (this.state.isEdit) {
      message.warning('表格中有未保存的数据!');
      return;
    }
    this.props.dispatch({
      type: 'productManageM/saveLiability',
      payload: {
        list: dataSource,
        productId: this.props.detailData.id,
      },
      callback: (data) => {
        if (data) {
          message.success('保存成功！');
          this.props.onCancel(true);
        }
      },
    });
  };

  // 下载模板
  download = () => {
    exportFile('gateway/portfolio-server/liability/download-template');
  };

  // 模板上传 拿到文件流调用后端接口
  getFile = (file) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('productId', this.props.detailData.id);
    this.props.dispatch({
      type: 'productManageM/uploadFile',
      payload: formData,
      callback: (data) => {
        if (data) {
          this.setState({
            // 页面状态恢复
            isEdit: false,
            currentRow: {},
          });
          this.formatDataSource(data); // 处理数据
          message.success('上传成功!');
        }
      },
    });
  };

  // 删除当前行
  deleteRow = (row) => {
    const { dataSource = [] } = this.state;
    const tempArr = dataSource.filter((item) => item.id != row.id);
    this.setState({
      dataSource: [...tempArr],
    });
  };

  // 新增表格行
  add = () => {
    const { dataSource = [] } = this.state;
    const temp = {
      isEdit: true,
      id: uuid(32),
      isNew: true, // 手动新增的标志
      portfolioCode: undefined,
      portfolioName: undefined,
      placement: undefined,
      startDate: undefined,
      endDate: undefined,
      interestRate: undefined,
      expectedYield: undefined,
    };
    dataSource.unshift(temp);
    this.setState({
      dataSource: [...dataSource],
      currentRow: _.cloneDeep(temp),
      isEdit: true, // 编辑状态
    });
  };

  // 取消编辑  恢复到编辑之前的行 编辑状态恢复
  cancelRow = (row) => {
    const { dataSource = [], currentRow } = this.state;
    if (row.isNew) {
      // 手动新增的数据，取消则删除行，清空
      dataSource.shift();
    } else {
      dataSource.map((item) => {
        if (item.id == row.id) {
          for (const i in currentRow) {
            item[i] = currentRow[i];
          }
          item.isEdit = false;
        }
      });
    }

    this.setState({
      dataSource: [...dataSource],
      currentRow: {},
      isEdit: false,
    });
  };

  // 点击编辑 当前行变为编辑状态
  clickEdit = (row) => {
    const { dataSource = [] } = this.state;
    if (this.state.isEdit) {
      message.warning('表格中有未保存的数据!');
      return;
    }
    let temp = {};
    dataSource.map((item) => {
      if (row.id == item.id) {
        item.isEdit = true;
        temp = item;
      }
    });
    this.setState({
      dataSource: _.cloneDeep(dataSource),
      isEdit: true,
      currentRow: _.cloneDeep(temp),
    });
  };

  // 保存当前行数据
  saveRow = (row) => {
    const { dataSource = [] } = this.state;
    // 判断是否都有值
    for (const key in row) {
      const element = row[key];
      if (element == undefined && typeof element !== 'number') {
        message.warning('请填写完整！');
        return;
      }
      if (!element && typeof element === 'number') {
        if (element == undefined || element == null) {
          message.warning('请填写完整！');
          return;
        }
        if (['expectedYield', 'interestRate', 'placement'].indexOf(key) > -1) {
          message.warning('数字必须大于0');
          return;
        }
      }
    }
    // 保存数据 将编辑状态改为false 并且清空 编辑之前的原始数据
    dataSource.map((item) => {
      if (row.id == item.id) {
        item.isEdit = false;
        item.isNew = false;
      }
    });
    this.setState({
      dataSource: _.cloneDeep(dataSource),
      isEdit: false,
      currentRow: {},
    });
  };

  // 表格页码变化
  handleTableChange = (pagination) => {
    const { pageSize, current } = pagination;
    this.setState({
      pageSize,
      currentPage: current,
    });
  };

  // 展示表格
  renderTable = () => {
    const { columns, dataSource, currentPage, pageSize } = this.state;
    return <TableC columns={columns} dataSource={dataSource} pageSize={pageSize} current={currentPage} onChange={this.handleTableChange} rowKey='id' />;
  };

  // 负载端维护列表弹窗
  showModal = () => {
    const { visible } = this.props;
    const { loading } = this.props;
    const newProps = {
      visible,
      title: '负债端维护',
      width: 1250,
      maskClosable: false,
    };
    return (
      <ModalC {...newProps} onCancel={this.closeModal} onOk={this.onOk} confirmLoading={loading.effects['productManageM/saveLiability'] === true}>
        <div>
          <div className={myStyle.myBtn}>
            <PrimaryC title='新增' onClick={this.add} disabled={this.state.isEdit == true} />
            <div>
              <UploadC
                style={{ marginRight: '16px', display: 'inline-block' }}
                title='模板上传'
                accept='.xlsx,.xls'
                showUploadList={false}
                type={2}
                onUpload={(e) => {
                  this.getFile(e);
                }}
                primaryProps={{ helper: '上传成功将覆盖当前列表' }}
              />
              <PrimaryGhostC title='模板下载' onClick={() => this.download()} />
            </div>
          </div>
          <div className={myStyle.myForm}>{this.renderTable()}</div>
        </div>
      </ModalC>
    );
  };

  render() {
    return <div>{this.showModal()}</div>;
  }
}
export default connect(({ productManageM, loading }) => ({
  productManageM,
  loading,
}))(Form.create()(MyModalC));
